package JDBC;

import java.sql.*;

/**
 * @Fou Jack of all trades and master of none.
 * @date 2022/1/6 11:22
 */
public class DAOTransaction {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement prestmt = null;
        try{
            //注册驱动
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            //通过注册驱动获取连接对象
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/daodemodb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC","root","root");
            //手动开启事务
            conn.setAutoCommit(false);
            String sql = "update t_user set money=money-? where id=?";
            prestmt = conn.prepareStatement(sql);
            prestmt.setDouble(1,111.11);
            prestmt.setInt(2,2);
            prestmt.addBatch();

            prestmt.setDouble(1,-111.11);
            prestmt.setInt(2,1);
            prestmt.addBatch();

            //批处理
            prestmt.executeUpdate();

            //提交事务
            conn.commit();
        }
        catch (SQLException e){
            //事务回滚
            conn.rollback();
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        finally {
            //释放资源
            if (conn!=null){
                conn.close();
            }
            if (prestmt!=null){
                prestmt.close();
            }
            if (rs!=null){
                rs.close();
            }
        }
    }
}
